﻿using System.Web;
using System.Web.Mvc;
using AMC.SubstitutionCache.Services;
using Orchard.DisplayManagement;

namespace AMC.SubstitutionCache
{
    public static class SubstitutionExtensions
    {
        public static SubstitutionContext SetSubstitutionContext(this IShape shape, SubstitutionContext context)
        {
            ((dynamic)shape).__substitutionContext = context;

            return context;
        }

        public static SubstitutionContext GetSubstitutionContext(this IShape shape)
        {
            return ((dynamic)shape).__substitutionContext as SubstitutionContext;
        }

        public static void SetGroupId(this IShape shape, string groupId)
        {
            ((dynamic)shape).__groupId = groupId;
        }

        public static string GetGroupId(this IShape shape)
        {
            return ((dynamic)shape).__groupId as string ?? string.Empty;
        }

        public static void SetRenderingSubstitution(this IShape shape, bool rendering = true)
        {
            ((dynamic)shape).__renderingSubstitution = rendering;
        }

        public static bool IsRenderingSubstitution(this IShape shape)
        {
            return (((dynamic)shape).__renderingSubstitution as bool?).GetValueOrDefault();
        }

        public static IHtmlString StartSubstitutionToken(this HtmlHelper @this, IShape shape)
        {
            var context = shape.GetSubstitutionContext();

            if (context == null || shape.IsRenderingSubstitution())
                return new HtmlString(string.Empty);

            return new HtmlString(string.Format(SubstitutionConstants.BeginSubstitutionTokenFormat, context.Key));
        }

        public static IHtmlString EndSubstitutionToken(this HtmlHelper @this, IShape shape)
        {
            var context = shape.GetSubstitutionContext();

            if (context == null || shape.IsRenderingSubstitution())
                return new HtmlString(string.Empty);

            return new HtmlString(string.Format(SubstitutionConstants.EndSubstitutionTokenFormat, context.Key));
        }

        internal static void SetIsCacheDebugMode(this HttpContextBase context, bool value)
        {
            context.Items[SubstitutionConstants.DebugModeKey] = value;
        }

        internal static bool IsCacheDebugMode(this HttpContextBase context)
        {
            return (bool)(context.Items[SubstitutionConstants.DebugModeKey] ?? false);
        }
    }
}